var dbmodel = require('../dbmodel/dbmodel.js');
var emailserver = require('./emailserver.js');
var user = dbmodel.model('users');

// 用户注册
exports.buildUser = function(name, email, pwd, res) {
	let data = {
		name: name,
		email: email,
		pwd: pwd,
		createTime: new Date()
	}

	// node大小写敏感，要区分User和user
	let User = new user(data);

	User.save(function(err, result) {
		if (err) {
			res.send(err);
		} else {
			emailserver.emailSignUp(email, name, res);
			res.send({
				status: 200,
				info: '用户注册成功'
			});
		}
	})
}

// 微信用户注册
exports.buildWxUser = function(req, res) {
	let wherestr = {
		'wxid': req.body.wxid
	};
	let out = {
		pwd:0
	}
	
	user.find(wherestr, out, function(err, result) {
		if (err) {
			res.send({
				status: 500
			});
		} else {
			// 匹配用户名或邮箱是否存在
			if (result == '') {
				let data = {
					name: req.body.name,
					wxid: req.body.wxid,
					email: '',
					pwd: '123456',
					createTime: new Date()
				}
				
				// node大小写敏感，要区分User和user
				let User = new user(data);
				
				User.save(function(err, result) {
					if (err) {
						res.send(err);
					} else {
						res.send({
							status: 200,
							info: '微信用户注册成功'
						});
					}
				})
			} else {
				res.send({
					status: 500,
					info: '用户已存在'
				})
			}
		}
	})
}